package com.superquan.springcloud;

import com.superquan.springcloud.entity.CommonResult;
import com.superquan.springcloud.entity.Payment;
import com.superquan.springcloud.service.PaymentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * 提供者
 * @title: PaymentController
 * @Author superQuan
 * @Date: 2022/3/28 22:44
 * @Version 1.0
 */
@RestController
@Slf4j
@RequestMapping(value = "/payment")
public class PaymentController {

    @Resource
    PaymentService paymentService;

    @Value("${server.port}")
    private String serverPort;

    @PostMapping(value = "/create")
    public CommonResult create(@RequestBody Payment payment) {
        int result = paymentService.create(payment);
        if (result > 0) {
            log.info("*****插入结果："+result);
            return new CommonResult(200, "插入数据库成功！，serverPort: "+serverPort, result);
        } else {
            return new CommonResult(444, "插入数据库失败！", null);
        }
    }

    @GetMapping(value = "/get/{id}")
    public CommonResult<Payment> getPaymentById(@PathVariable("id") Long id) {
        log.info("【开始进入】：provide-payment8001");
        log.info("【传入参数】id:"+id);
        Payment payment = paymentService.getPaymentById(id);
        if (payment != null) {
            log.info("【查询成功】"+payment.toString());
            return new CommonResult(200, "查询成功！，serverPort: "+serverPort, payment);
        } else {
            return new CommonResult(444, "没有对应记录,查询ID: " + id, null);
        }
    }

    @GetMapping(value = "/lb")
    public String getPaymentLB() {
        return serverPort;//返回服务接口
    }

    /**
     * 模拟OpenFeign超时机制
     * OpenFeign默认等待1秒钟，超过后报错
     * @return
     */
    @GetMapping(value = "/feign/timeout")
    public String paymentFeignTimeout(){
        try{
            //openfeign-ribbon,客户端默认等待一秒钟
            //此处休眠3秒，超过客户端默认等待的一秒钟
            TimeUnit.SECONDS.sleep(3);
        }catch (InterruptedException e){
            e.printStackTrace();
        }
        return serverPort;
    }
}
